package examples.game;

import java.util.Random;

/**
 * @author Orlin Tomov
 *
 */
public class Digits implements Comparable<Digits> {

	private int[] digits;

	/**
	 * digits by array
	 * @param digits
	 */
	public Digits(int[] digits) {
		this.digits = digits.clone();
	}

	/**
	 * random digits
	 */
	Digits() {
		digits = new int[BullsAndCows.NUM_DIGITS];
		for (int i = 0; i < BullsAndCows.NUM_DIGITS; i++) {
			int n = getRandom();
			boolean same = false;
			do {
				for (int j = 0; j < i; j++) {
					same = (n == digits[j]);
					if (same) {
						n = getRandom();
						break;
					}
				}
			} while (same);
			digits[i] = n;
		}
	}

	/**
	 * next digit
	 * @param prev
	 */
	Digits(Digits prev) {
		digits = prev.digits.clone();
		int i = 0;
		boolean next = true;
		while(true) {
			if (next) {
				digits[i] = (digits[i] + 1) % 10;
				if (digits[i] == 0) {
					i++;
					if (i == BullsAndCows.NUM_DIGITS) {
						i--;
						next = false;
					}
					continue;
				}
			}
			next = true;
			boolean same = false;
			for (int j = i+1; j < BullsAndCows.NUM_DIGITS; j++) {
				same = (digits[i] == digits[j]);
				if (same) break;
			}
			if (!same) {
				if (i > 0) {
					i--;
					next = false;
				} else {
					return;
				}
			}
		}
	}

	public int[] get() {
		return digits.clone();
	}

	public int get(int index) {
		return digits[index];
	}

	/**
	 * 
	 * @return random number between 0 and 9
	 */
	private int getRandom() {
		return Math.abs(new Random().nextInt() % 10);
	}

	@Override
	public int compareTo(Digits other) {
		for (int i = 0; i < BullsAndCows.NUM_DIGITS; i++) {
			if (digits[i] != other.get(i))
				return new Integer(digits[i]).compareTo(other.get(i));
		}
		return 0;
	}

	@Override
	public boolean equals(Object other) {
		if (other instanceof Digits) {
			return equals((Digits)other);
		}
		return false;
	}

	public boolean equals(Digits other) {
		return this.compareTo(other) == 0;
	}

	@Override
	public String toString() {
		String line = "";
		for (int i = 0; i < BullsAndCows.NUM_DIGITS; i++) {
			line += digits[i];
		}
		return line;
	}
}
